<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JD购物车</title>
    <link rel="stylesheet" href="./lib/css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/cart.css">
    <script src="http://at.alicdn.com/t/c/font_4000250_pbgp7djttj.js"></script>
    <script src="./lib/axios.js"></script>
    <script src="./lib/ajax.js"></script>
</head>

<body>
    <!-- 
         <svg class="icon" aria-hidden="true">
    <use xlink:href="#icon-tubiaozhizuomoban"></use>
</svg>
     -->

    <!-- 第一部分 nav -->
    <div class="nav">
        <div class="navC">
            <div class="left">
                <ul>
                    <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-fangzi"></use>
                        </svg>
                        <span><a href="./index.html" target="_blank">京东首页</a></span>
                    </li>
                    <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon--"></use>
                        </svg>
                        <span>河北</span>
                    </li>
                </ul>
            </div>
            <div class="right">
                <ul>
                    <li><a href="#">我的</a></li>
                    <li><a href="#">我的订单</a></li>
                    <li><a href="#">我的京东</a></li>
                    <li><a href="#">企业采购</a></li>
                    <li><a href="#">商家服务</a></li>
                    <li><a href="#">网站导航</a></li>
                    <li><a href="#">手机京东</a></li>
                    <li><a href="#">网站无障碍</a></li>
                </ul>
            </div>
        </div>
    </div>

    <!-- 第二部分 banner -->
    <div class="banner">
        <div class="bannerTop">
            <img src="./images/login01.png" alt="">
            <div>
                <input type="text" placeholder="查询心爱物品~.~">
                <span>搜索</span>
            </div>
        </div>
        <div class="bannerBottom">
            <div>
                <p>全部商品</p>
                <p class="numTotal"></p>
            </div>
            <div>
                <p>配送至:</p>
                <input type="text" value="河南郑州市中鸿花园">
            </div>
        </div>
    </div>

    <!-- 第三部分 cart -->
    <div class="cart">
        <div class="cartC">
            <table class="table table-striped table-hover">
                <!-- js 插入 -->
            </table>
            <div class="cartBottom">
                <div class="cartLeft">
                    <p>
                        <input class="checkAll form-check-input" type="checkbox" id="checkss" role="switch">
                        <label for="checkss">全选</label>
                    </p>
                    <p>删除选中的商品</p>
                    <p>移入关注</p>
                    <p>清理购物车</p>
                </div>
                <div class="cartRight">
                    <p>已选择<span class="goodsNum">00</span>件商品</p>
                    <p>总价 : <span class="totalPrice">0.00</span></p>
                    <p>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-tubiaozhizuomoban"></use>
                        </svg>
                    </p>
                    <p>
                        去结算
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        /* 1. 渲染页面 */
        // 基本url
        const baseURL = 'http://localhost:8888';
        // 容器
        let table = document.querySelector('.table');

        // 交互，获取数据，渲染基本页面
        axios('/cart/list', {
            headers: {
                "authorization": localStorage.getItem("token"),
            },
            baseURL,
            params: {
                id: localStorage.getItem('uid')
            }
        }).then(res => {
            res = res.data.cart;
            // console.log(res);
            table.innerHTML = `
                <tr class="list" style="background-color: rgb(243, 243, 243);">
                    <td>
                        <input class="checkAll form-check-input" id='che' type="checkbox" role="switch">
                        <label for="che">全选</label>
                    </td>
                    <td>商品</td>
                    <td>标题</td>
                    <td>单价</td>
                    <td>折扣</td>
                    <td>数量</td>
                    <td>删除</td>
                </tr>`;
            table.innerHTML += res.map(item => `
            <tr class="list1">
                    <td style="width: 70px;">
                        <input class="checks form-check-input" style="width:20px; height:20px;" type="checkbox" role="switch">
                    </td>
                    <td style="width: 100px;"><img style="width:150px; height: 150px;" src="${item['img_small_logo']}"></td>
                    <td style="width: 200px;">${item.title}</td>
                    <td>${item.price}</td>
                    <td class="currentPrice">${item['current_price']}</td>
                    <td style="width: 300px;">
                        <div class="input-group">
                            <img class="plus" data-id="${item["goods_id"]}" style="width:40px;height: 40px;" src="./images/jia.png">
                            <input type="text" class="nums form-control" value="${item['cart_number']}" data-id="${item["goods_id"]}">
                            <span class="input-group-text">￥</span>
                            <span class="onePrice input-group-text" style="width:100px;">${parseFloat(item['current_price'] * item['cart_number']).toFixed(2)}</span>
                            <img class="minus" data-id="${item["goods_id"]}" style="width:35px;height: 35px; margin-top: 3px;" src="./images/jian.png">
                        </div>
                    </td>
                    <td style="width: 150px;">
                        <button type="button" class="btn btn-outline-info" data-id="${item["goods_id"]}">移除</button>
                    </td>
                </tr>`).join('');

            // 全选
            let checkAlls = document.querySelectorAll('.checkAll');
            // 单选
            let checkItems = document.querySelectorAll('.checks');
            // 总价
            let totalPrice = document.querySelector('.totalPrice');
            // 单总
            let onePrice = document.querySelectorAll('.onePrice');
            // 选中几件商品
            let goodsNum = document.querySelector('.goodsNum');
            // 单个商品数量
            let cartNum = document.querySelectorAll('.nums');
            // 加
            let plus = document.querySelectorAll('.plus');
            // 减
            let minus = document.querySelectorAll('.minus');
            // 移除
            let del = document.querySelectorAll('.btn');
            // 折扣价
            let currentPrice = document.querySelectorAll('.currentPrice');
            // 全部商品总数
            let numTotal = document.querySelector('.numTotal');

            res.forEach(item => {
                numTotal.innerText = numTotal.innerText / 1 + item['cart_number'];
            })

            /* 1. 单选多选 */
            for (let i = 0; i < checkAlls.length; i++) {
                checkAlls[i].onclick = function () {
                    if (i == 0) {
                        checkAlls[1].checked = checkAlls[0].checked;
                    } else {
                        checkAlls[0].checked = checkAlls[1].checked;
                    }
                    checkItems.forEach(item => {
                        item.checked = checkAlls[i].checked;
                    });
                    getTotalPrice();
                };
            }
            checkItems.forEach((item, index) => {
                item.onclick = () => {
                    let checkedS = document.querySelectorAll('.checks:checked');
                    if (checkedS.length == checkItems.length) {
                        checkAlls[0].checked = true;
                        checkAlls[1].checked = true;
                    } else {
                        checkAlls[0].checked = false;
                        checkAlls[1].checked = false;
                    }
                    getTotalPrice();
                }
            })

            /* 2.  */
            for (let i = 0; i < plus.length; i++) {

                // 加
                plus[i].onclick = function () {
                    let pid = this.getAttribute('data-id');
                    console.log(pid);
                    setGoodsNum(pid, 1, i, true);
                    // getTotalPrice();
                    // setTotalGoods();
                }

                // 减
                minus[i].onclick = function () {
                    let pid = this.getAttribute('data-id');
                    console.log(pid);
                    setGoodsNum(pid, 1, i, false);
                    // getTotalPrice();
                }

                // 数量
                cartNum[i].onchange = function () {
                    let pid = this.getAttribute('data-id');
                    let num = this.value / 1;
                    setGoodsNum(pid, num, i);
                    // getTotalPrice();
                }

                // 移除
                del[i].onclick = function () {
                    let pid = this.getAttribute('data-id');
                    axios('/cart/remove', {
                        baseURL,
                        headers: {
                            "authorization": localStorage.getItem("token"),
                        },
                        params: {
                            id: localStorage.getItem('uid') / 1,
                            goodsId: pid
                        }
                    }).then(res =>
                        console.log(res)
                    ).catch(err =>
                        console.log(err)
                    ).finally(() => {
                        getTotalPrice();
                        location.href = '03-cart.html';
                    })
                } // del
            }

            // 加，减，修改数量，动态更新总数，总价，单总
            function setGoodsNum(goodsId, num, index, bool) {
                axios("/cart/list", {
                    baseURL,
                    headers: {
                        "authorization": localStorage.getItem("token"),
                    },
                    params: {
                        id: localStorage.getItem('uid'),
                    }
                }).then(res => {
                    let data = res.data.cart;

                    let goodsNum = 0;
                    data.forEach((item) => {
                        if (item["goods_id"] == goodsId) {
                            goodsNum = item["cart_number"];
                        }
                    })

                    if (bool) {
                        goodsNum += num;
                    } else if (bool == undefined) {
                        goodsNum = num;
                    } else {
                        goodsNum -= num;
                    }

                    // 数量修改成功，才能计算单总和总价
                    ajaxx({
                        type: 'post',
                        url: baseURL + '/cart/number',
                        author: true,
                        params: {
                            id: localStorage.getItem('uid'),
                            goodsId,
                            number: goodsNum,
                        },
                        fn(res) {
                            let info = JSON.parse(res);
                            if (info.code == 1) {
                                console.log("success:", info);
                                data.forEach((item, index) => {
                                    if (item["goods_id"] == goodsId) {
                                        cartNum[index].value = goodsNum;
                                    }
                                });
                                // 需要等数量修改完才能计算单总
                                getOnePrice(index);
                                // 【注意】 修改完数量还需要计算总价，动态变动
                                getTotalPrice();
                            } else {
                                console.log("error:", info);
                            }
                        }, // fn
                    }); // ajaxx
                }).finally(() => {
                    setTotalGoods();
                })
            } // setGoodsNum

            // 全部商品总数，修改数据后，需要重新获取购物车列表，不可在用旧的列表
            function setTotalGoods() {
                axios('/cart/list', {
                    headers: {
                        "authorization": localStorage.getItem("token"),
                    },
                    baseURL,
                    params: {
                        id: localStorage.getItem('uid')
                    }
                }).then(res => {
                    res = res.data.cart;
                    let num = 0;
                    res.forEach(item => {
                        num += item['cart_number'];
                    });
                    numTotal.innerText = num;
                }).catch(err => console.log('error:', err))
            }


            // 计算单总
            function getOnePrice(i) {
                onePrice[i].innerText = parseFloat(currentPrice[i].innerText * cartNum[i].value).toFixed(2);
            }

            // 计算总价，不能放在外面
            function getTotalPrice() {
                let total = 0;
                let selectGoodsNum = 0
                checkItems.forEach((item, index) => {
                    if (item.checked) {
                        total += onePrice[index].innerText / 1;
                        selectGoodsNum = selectGoodsNum + cartNum[index].value / 1;
                    }
                })

                totalPrice.innerText = parseFloat(total).toFixed(2);
                goodsNum.innerText = selectGoodsNum;
            };
        })

    </script>
</body>

</html>